import { ref, onUnmounted } from 'vue';

/**
 * 视频录制和上传的hooks
 * @param {Object} options 配置选项
 * @param {string} options.uploadFolder 上传文件夹路径，如 'task-video'
 * @param {string} options.videoName 视频文件名（不含扩展名）
 * @returns {Object} 返回录制相关的方法和状态
 */
export function useVideoRecorder(options = {}) {
  const { uploadFolder = 'task-video', videoName = 'default_video' } = options;
  

  
  // 视频录制相关状态
  const video_recorder = ref(null);
  const video_chunks = ref([]);
  const video_stream = ref(null);
  const is_recording = ref(false);
  
  // 腾讯云COS存储桶信息
  const COS_CONFIG = {
    bucket: import.meta.env.VITE_COS_CONFIG_BUCKET,
    region: import.meta.env.VITE_COS_REGION,
    base_url: import.meta.env.VITE_COS_CONFIG_BASEURL
  };
  
  /**
   * 开始视频录制
   */
  const startRecording = async () => {
    try {
      video_stream.value = await navigator.mediaDevices.getUserMedia({ 
        video: { 
          width: 1280, 
          height: 720,
          frameRate: 30
        }, 
        audio: true 
      });
      
      // 针对electron环境优化录制选项
      let recording_options = { 
        audioBitsPerSecond: 128000,
        videoBitsPerSecond: 2500000, // 2.5Mbps 提高视频质量
        mimeType: 'video/webm;codecs=vp9' // electron环境下webm格式支持更好
      };
      
      // 如果不支持vp9，尝试其他格式
      if (!MediaRecorder.isTypeSupported('video/webm;codecs=vp9')) {
        if (MediaRecorder.isTypeSupported('video/webm;codecs=vp8')) {
          recording_options.mimeType = 'video/webm;codecs=vp8';
        } else if (MediaRecorder.isTypeSupported('video/webm')) {
          recording_options.mimeType = 'video/webm';
        } else {
          recording_options.mimeType = undefined;
        }
      }
      
      video_recorder.value = new MediaRecorder(video_stream.value, recording_options);
      
      video_recorder.value.ondataavailable = (event) => {
        if (event.data.size > 0) {
          video_chunks.value.push(event.data);
        }
      };
      
      video_recorder.value.start();
      is_recording.value = true;
      return true;
    } catch (error) {
      ElMessage.error('启动视频录制失败:'+error.message);
      return false;
    }
  };
  
  /**
   * 停止视频录制
   */
  const stopRecording = () => {
    return new Promise((resolve) => {
      if (video_recorder.value && is_recording.value) {
        video_recorder.value.onstop = () => {
          is_recording.value = false;
          resolve(true);
        };
        video_recorder.value.stop();
      } else {
        resolve(false);
      }
    });
  };
  
  /**
   * 上传视频到腾讯云COS
   */
  const uploadVideo = async () => {
    try {
      if (video_chunks.value.length === 0) {
        console.error('没有视频数据可上传');
        return false;
      }
      // 创建视频文件
      const video_blob = new Blob(video_chunks.value, { 
        type: video_recorder.value.mimeType,
        lastModified: Date.now()
      });
      
      // 根据实际录制格式生成文件名
      let file_extension = '.webm'; // 默认webm格式
      if (video_recorder.value.mimeType && video_recorder.value.mimeType.includes('mp4')) {
        file_extension = '.mp4';
      }
      const file_name = `${videoName}${file_extension}`;
      const upload_url = `${COS_CONFIG.base_url}/${uploadFolder}/${file_name}`;
      
      // 使用PUT请求直接上传到公有读写存储桶
      const response = await fetch(upload_url, {
        method: 'PUT',
        body: video_blob,
        headers: {
          'Content-Type': video_recorder.value.mimeType
        }
      });
      
      if (response.ok) {
        return { success: true, url: upload_url, filename: file_name };
      } else {
        ElMessage.error('视频上传失败:'+ response.statusText);
        return { success: false, error: response.statusText };
      }
    } catch (error) {
      ElMessage.error('视频上传错误:'+ e.message);
      return { success: false, error: error.message };
    }
  };
  
  /**
   * 停止录制并上传视频
   */
  const stopAndUpload = async () => {
    const stopped = await stopRecording();
    if (stopped) {
      return await uploadVideo();
    }
    return { success: false, error: '停止录制失败' };
  };
  
  /**
   * 清理资源
   */
  const cleanup = () => {
    if (video_stream.value) {
      video_stream.value.getTracks().forEach(track => track.stop());
      video_stream.value = null;
    }
    video_recorder.value = null;
    video_chunks.value = [];
    is_recording.value = false;
  };
  
  // 组件卸载时清理资源
  onUnmounted(() => {
    cleanup();
  });
  
  return {
    // 状态
    is_recording,
    
    // 方法
    startRecording,
    stopRecording,
    uploadVideo,
    stopAndUpload,
    cleanup
  };
}